<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 17/3/2
 * Time: 17:08
 */

namespace Warehouse\Service;

use Inbound\Service\PrepareneedsService;
use Inbound\Service\PublicInfoService;
use Inbound\Service\PublicPlugService;

class InventoryService {
    public $inventories = NULL;
    public $real_inventories = NULL;
    public $warehouseorders = NULL;
    public $deliveryorders = NULL;
    public $fbaInboundShipmentPlan = NULL;
    public $attrLog = NULL;
    public $sku_cnname = NULL;
    public $fbaPrepareNeedsDetails = NULL;
    public $pandians = NULL;
    public $storage = NULL;
    public $balance = NULL;

    //查询记录总数
    public $count = 0;
    //页面展示包含页面样式
    public $page = array ();
    //数据
    public $data = array ();

    public $inventories_data = array ();

    public $nowtime;

    public function __construct ($table = '', $param = array ()) {
        $this->nowtime                = date('Y-m-d H:i:s', time());
        $this->inventories            = D('Warehouse/Inventories', 'Model');
        $this->real_inventories       = D('Warehouse/RealInventories', 'Model');
        $this->warehouseorders        = D('Warehouse/StockIn', 'Model');
        $this->deliveryorders         = D('Warehouse/StockOut', 'Model');
        $this->purchaseorders         = D('Warehouse/PurchaseOrders', 'Model');
        $this->fbaInboundShipmentPlan = D('Warehouse/FbaInboundShipmentPlan', 'Model');
        $this->sku_cnname             = D('Warehouse/SkuCnname', 'Model');
        $this->fbaPrepareNeedsDetails = D('Warehouse/FbaPrepareNeedsDetails', 'Model');
        $this->pandians               = D('Warehouse/Pandians', 'Model');
        $this->stockIn                = D('Warehouse/StockIn', 'Model');
        $this->storage                = D('Warehouse/Storage', 'Model');
        $this->balance                = D('Warehouse/Balance', 'Model');
    }

    /**
     * 获取实时库存
     * @param array $_array
     * @param bool  $flag
     * @return mixed
     */
    public function getRealInventories (&$_array = array (), $flag = TRUE) {
        $_array = empty($_array)?$_GET:$_array;
        $model  = $this->real_inventories->get_real_inventories_model($_array, $flag);
        if ($flag) {
            $realinventories = clone $model;
            $this->count     = $realinventories->count();//数量
            $Page            = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page      = $Page->show();// 分页显示输出

            $model->order("id desc")
                ->limit($Page->firstRow.','.$Page->listRows);
        }

        $result = $model->select();
        $result = $this->format_inventories_data($result, FALSE);

        return $result;
    }

    /**
     * @param $array
     * @return string
     * 处理批量查询sku
     */
    public  function  handle_sku($array){
        $skus = str_replace(array("\r\n", "\r", "\n"),";",$array);  //处理换行
        $skus = str_replace(" ",";",$skus);  //处理换行
        $skus = str_replace(";",",",$skus);  //处理换行
        $skus = str_replace("，",",",$skus);  //处理中文逗号
        $skus = rtrim($skus,",");
        $skus = array_filter(explode(",",$skus));
        $skus = array('in',$skus);
        return $skus;
    }

    /**
     * 非出口退税库存信息
     * @param $sku
     * @return mixed
     */
    public function getInventoriesInfo (&$_array) {
        //期初库存
        $open                   = $this->inventories->get_sku_open_count($_array);
        $stocks['open_stock']   = $open['quantity'];
        $stocks['sku']          = $open['sku'];
        $stocks['sku_name']     = $open['sku_name'];
        $stocks['sku_standard'] = $open['sku_standard'];
        //入库量
        $wo               = $this->warehouseorders->getSkuWarehouseCount($_array);
        $stocks['wo_num'] = $wo['wo_num'];
        //出库量
        $do               = $this->deliveryorders->getSkuDeliveryCount($_array);
        $stocks['do_num'] = $do['do_num'];
        //实际库存
        $stocks['stock'] = $this->real_inventories->get_sku_real_inventories($_array);
        //在途库存
        $stocks['onway_num'] = $this->purchaseorders->onway_inventory($_array);
        //订单占用未发
        $stocks['order_occupy_num'] = $this->fbaInboundShipmentPlan->get_sku_occupied_num($_array) + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($_array, 0);
        //实际库存可用量=实际库存量-订单总未发量
        $stocks['actual_available_num'] = $stocks['stock'] - $stocks['order_occupy_num'];
        //总可用量
        $stocks['all_available_num'] = $stocks['actual_available_num'] + $stocks['onway_num'];
        //所有站点可用量=所有站点实际库存量-所有站点订单总未发量
        $stocks['all_site_num'] = $this->get_all_site_num($_array);

        //期初成本
        $stocks['open_cost'] = $open['cost'];
        //本期入成本
        $stocks['wo_cost'] = $wo['cost'];
        //本期出成本
        $stocks['do_cost'] = $do['cost'];

        return $stocks;
    }

    /**
     * 出口退税库存信息
     * @param $sku
     * @return mixed
     */
    public function getTaxInventoriesInfo (&$_array) {
        //期初库存
        $open                   = $this->inventories->get_tax_sku_open_count($_array);
        $stocks['open_stock']   = $open['quantity'];
        $stocks['sku']          = $open['sku'];
        $stocks['sku_name']     = $open['sku_name'];
        $stocks['sku_standard'] = $open['sku_standard'];
        //入库量
        $wo               = $this->warehouseorders->getTaxSkuWarehouseCount($_array);
        $stocks['wo_num'] = $wo['wo_num'];
        //出库量
        $do               = $this->deliveryorders->getTaxSkuDeliveryCount($_array);
        $stocks['do_num'] = $do['do_num'];
        //实际库存
        $stocks['stock'] = $this->real_inventories->get_tax_sku_real_inventories($_array);
        //在途库存
        $stocks['onway_num'] = $this->purchaseorders->tax_onway_inventory($_array);
        //订单占用未发
        $stocks['order_occupy_num'] = $this->fbaInboundShipmentPlan->get_tax_sku_occupied_num($_array) + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($_array, 1);
        //实际库存可用量=实际库存量-订单总未发量
        $stocks['actual_available_num'] = $stocks['stock'] - $stocks['order_occupy_num'];
        //总可用量
        $stocks['all_available_num'] = $stocks['actual_available_num'] + $stocks['onway_num'];
        //所有站点可用量=所有站点实际库存量-所有站点订单总未发量
        $stocks['all_site_num'] = $this->get_all_site_num($_array);

        //期初成本
        $stocks['open_cost'] = $open['cost'];
        //本期入成本
        $stocks['wo_cost'] = $wo['cost'];
        //本期出成本
        $stocks['do_cost'] = $do['cost'];//var_dump($stocks);exit;

        return $stocks;
    }

    /**
     * @param $_array
     * @return array|bool
     * 自动调拨合法性验证
     * khq 2017.4.20
     */
    public function check_auto_data ($_array) {
        if ($_array['sku'] == '' || $_array['enterprise_dominant'] == '' || $_array['export_tax_rebate'] == '' || $_array['site_id'] == '' || $_array['quantity'] == '') {
            return array (
                'status'  => FALSE,
                'message' => '数据不全,不能进行调拨,请联系IT郭群超处理'
            );
        }
        $sku_name = PublicInfoService::getSkuCnname_bak($_array['sku']);
        if (strpos($sku_name, '美规') !== FALSE) { //美规：美国，加拿大
            $allow_site = array (
                107,
                21
            );
            if (!in_array($_array['site_id'], $allow_site)) {
                return array (
                    'status'  => FALSE,
                    'message' => '美规sku不允许调拨到当前站点!'
                );
            }
        }
        if (strpos($sku_name, '欧规') !== FALSE) { //欧规：法国、德国、西班牙、意大利
            $allow_site = array (
                38,
                41,
                94,
                54
            );
            if (!in_array($_array['site_id'], $allow_site)) {
                return array (
                    'status'  => FALSE,
                    'message' => '欧规sku不允许调拨到当前站点!'
                );
            }
        }
        if (strpos($sku_name, '日规') !== FALSE) { //日规（日本）
            $allow_site = array (55);
            if (!in_array($_array['site_id'], $allow_site)) {
                return array (
                    'status'  => FALSE,
                    'message' => '日规sku不允许调拨到当前站点!'
                );
            }
        }
        if (strpos($sku_name, '英规') !== FALSE) { //英规（英国）
            $allow_site = array (106);
            if (!in_array($_array['site_id'], $allow_site)) {
                return array (
                    'status'  => FALSE,
                    'message' => '英规sku不允许调拨到当前站点!'
                );
            }
        }
        return TRUE;
    }

    /**
     * @param $_array
     * @return array|bool
     * 手动调拨合法性验证
     * khq 2017.4.20
     */
    public function check_move_site_data ($_array) {
        $sku_name = PublicInfoService::getSkuCnname_bak($_array['sku']);
        if (strpos($sku_name, '美规') !== FALSE) { //美规：美国，日本加拿大
            $allow_site = array (
                107,
                55,
                21
            );
            if (!in_array($_array['site_id'], $allow_site)) {
                return array (
                    'status'  => FALSE,
                    'message' => '美规sku不允许调拨到当前站点!'
                );
            }
        }
        if (strpos($sku_name, '欧规') !== FALSE) { //欧规：法国、德国、西班牙、意大利
            $allow_site = array (
                38,
                41,
                94,
                54
            );
            if (!in_array($_array['site_id'], $allow_site)) {
                return array (
                    'status'  => FALSE,
                    'message' => '欧规sku不允许调拨到当前站点!'
                );
            }
        }
        if (strpos($sku_name, '日规') !== FALSE) { //日规（日本）
            $allow_site = array (55);
            if (!in_array($_array['site_id'], $allow_site)) {
                return array (
                    'status'  => FALSE,
                    'message' => '日规sku不允许调拨到当前站点!'
                );
            }
        }
        if (strpos($sku_name, '英规') !== FALSE) { //英规（英国）
            $allow_site = array (106);
            if (!in_array($_array['site_id'], $allow_site)) {
                return array (
                    'status'  => FALSE,
                    'message' => '英规sku不允许调拨到当前站点!'
                );
            }
        }
        return TRUE;
    }

    /**
     * $_array 公司主体,站点,退税方式,sku,需求数量
     * 1.查询当前站点可调用量 够用false
     * 2.查询所有站点可调用量 不够用则false
     * 3.查询各个站点的数量(除去当前站点) 待调拨数量为:需求数量-当前站点可调用量
     * 4.遍历各个站点,取得各个站点可调用量进行调拨
     * 备货申请的自动调拨站点
     * khq 2017.4.16
     */
    public function auto_move_site ($_array) {
        $flag = $this->check_auto_data($_array);                                       //自动调拨合法性验证
        if ($flag !== TRUE) {
            return array (
                'status'  => FALSE,
                'message' => $flag['message']
            );
        }
        //1.
        $num = $this->get_site_available_num($_array);
        if ($num >= $_array['quantity']) {
            return array (
                'status'  => FALSE,
                'message' => '站点库存够用,不需要进行调拨'
            );
        }
        //2.
        $total_num = $this->get_all_site_num($_array);
        if ($total_num < $_array['quantity']) {
            return array (
                'status'  => FALSE,
                'message' => '该sku所有站点总库存不够,无法进行调拨'
            );
        }
        //3.
        $where  = array (
            'sku'                 => $_array['sku'],
            'enterprise_dominant' => $_array['enterprise_dominant'],
            'export_tax_rebate'   => $_array['export_tax_rebate'],
            'site_id'             => array (
                'neq',
                $_array['site_id']
            )
        );
        $result = $this->storage->get_all_site_availiable($where);                  //入库单可用数量信xi
        var_dump($result);exit;
        $map    = array (
            'sku'                 => trim($_array['sku']),
            'enterprise_dominant' => $_array['enterprise_dominant'],
            'export_tax_rebate'   => $_array['export_tax_rebate'],
        );
        $re_num = $_array['quantity'] - $num;           //需要调拨数量
        /*
         * 1.求得相同公司主体,退税方式,sku下不同站点库存数组
         * 2.遍历数组求得对应站点可调拨量
         * 3.求改站点可调拨量对应储位的库存数组
         * 4.遍历库存数组,生成站点调拨的数据结构
         * 5.执行站点调拨
         */
        $move_arr = array (
            'sku'     => trim($_array['sku']),
            'site_id' => $_array['site_id']
        );
        $sites    = PublicInfoService::get_site_array();
        foreach ($result as $K1 => $v1) {
            if ($re_num <= 0) {
                break;
            }
            $map['site_id'] = $v1['site_id'];
            $site_num       = $this->get_site_available_num($map);    //当前站点可调用量 站点实际库存-订单占用
            $storage_sum    = $this->storage->get_site_availiable($map); //获取当前站点下库存的储位分布
            foreach ($storage_sum as $k2 => $v2) {
                if ($re_num <= 0) {
                    break 2;
                }
                $available_quantity = $v2['available_quantity'];
                if ($available_quantity > $site_num) {  //储位数量大于当前站点可调用量,则选可调用量
                    $available_quantity = $site_num;
                }
                if ($available_quantity >= $re_num) {  //储位数量大于需要的调拨数量,则选需要的调拨数量
                    $available_quantity = $re_num;
                }
                if ($available_quantity <= 0) {
                    continue;
                }

                $move_arr['available_quantity'][]  = $available_quantity;
                $move_arr['site'][]                = $sites[$v2['site_id']];
                $move_arr['storage_position'][]    = $v2['storage_position'];
                $move_arr['export_tax_rebate'][]   = $v2['export_tax_rebate'];
                $move_arr['enterprise_dominant'][] = $v2['enterprise_dominant'];
                $re_num -= $available_quantity;                         //分配数量后,需要调拨数量减少
                $available_quantity = 0;
            }
        }
        $flag = $this->warehouseorders->site_move($move_arr);
        return array (
            'status'  => $flag,
            'message' => '自动调拨失败'
        );
    }

    /**
     * @param $_arr -sku,site_id,enterprise_dominant,export_tax_rebate
     * @return int
     *              查出当前站点可用的库存
     *              实际可用库存-订单占用库存
     *              khq 2017.4.16
     */
    public function get_site_available_num ($_arr) {
        $_array = array (
            'sku'                 => $_arr['sku'],
            'site_id'             => $_arr['site_id'],
            'enterprise_dominant' => $_arr['enterprise_dominant'],
            'export_tax_rebate'   => $_arr['export_tax_rebate']
        );
        $num    = 0;
        if ($_array['export_tax_rebate'] == 1) {
            $avl_num = $this->real_inventories->get_tax_sku_real_inventories($_array);             //1.实际库存
            //订单占用未发
            $order_occupy_num = $this->fbaInboundShipmentPlan->get_tax_sku_occupied_num($_array)   //2.查出当前站点订单占用库存
                + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($_array, 1);
            $num              = $avl_num - $order_occupy_num;
        } else {
            $avl_num          = $this->real_inventories->get_sku_real_inventories($_array);
            $order_occupy_num = $this->fbaInboundShipmentPlan->get_sku_occupied_num($_array) + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($_array, 0);
            $num              = $avl_num - $order_occupy_num;
        }
        return $num;
    }

    /**
     * @param $_array -sku,enterprise_dominant,export_tax_rebate
     * @return int 所有站点总可调用量
     *                khq 2017.4.16
     */
    public function get_all_site_num ($_array) {
        $where     = array (
            'sku'                 => $_array['sku'],
            'enterprise_dominant' => $_array['enterprise_dominant'],
            'export_tax_rebate'   => $_array['export_tax_rebate']
        );
        $num_data  = $this->real_inventories->get_Site_Quantity($where);
        $total_num = 0;
        foreach ($num_data as $K => $v) {
            $where['site_id'] = $v['site_id'];
            $total_num += $this->get_site_available_num($where);
        }
        return $total_num;
    }

    /**
     * @param $where -sku and available_quantity>0
     * @return mixed
     *               获取入库单可用库存信息
     */
    public function get_site_availiable ($where) {
        $result   = $this->storage->get_site_availiable($where);                                 //入库单可用数量信息
        $sites    = PublicInfoService::get_site_array();
        $companys = PublicInfoService::get_company_array();
        foreach ($result as $k => $v) {
            $result[$k]['site_id'] = $sites[$v['site_id']]?$sites[$v['site_id']]:'';
            $result[$k]['company'] = $companys[$v['enterprise_dominant']]?$companys[$v['enterprise_dominant']]:'';
            $result[$k]['tuisui']  = $v['export_tax_rebate'] == 1?'出口退税':'非出口退税';
            $where_map             = array (
                'sku'                 => $v['sku'],
                'enterprise_dominant' => $v['enterprise_dominant'],
                'site_id'             => $v['site_id']
            );
            if ($v['export_tax_rebate'] == 1) {
                $result[$k]['order_occupy_num'] = $this->fbaInboundShipmentPlan->get_tax_sku_occupied_num($where_map)
                    + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($where_map, 1);    //订单占用库存
            } else {
                $result[$k]['order_occupy_num'] = $this->fbaInboundShipmentPlan->get_sku_occupied_num($where_map)
                    + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($where_map, 0);
            }
            $result[$k]['available_quantity'] -= $result[$k]['order_occupy_num'];
        }
        return $result;
    }

    /**
     * 获取sku的对应储位的实际库存
     * @param $skus
     * @return mixed
     */
    public function getStorageInventories ($_array) {
        $model = $this->warehouseorders;

        $skuss               = is_array($_array['sku'])?$_array['sku']:array ($_array['sku']);
        $enterprise_dominant = $_array['enterprise_dominant'];
        $site_id             = $_array['site_id'];

        return $model->get_storage_inventories('', $skuss, $enterprise_dominant, $site_id)
            ->order('export_tax_rebate DESC')
            ->select();
    }

    /**
     * 每月月初更新期初库存
     */
    public function update_open_inventories () {
        $inven_model = $this->inventories;
        $sku_model   = $this->sku_cnname;

        //先删除当月已经存在的sku
        $inven_model->delete_inventories();

        $skus = $sku_model->get_skus();

        //期初日期
        $open_date = date('Y-m-01');
        while ($skus_arr = array_splice($skus, 0, 5000)) {
            //新增当月所有非出口退税的的sku
            $data = $sku_model->get_skus_info($skus_arr);
            foreach ($data as &$sku) {
                $sku['inventory_date']    = $open_date;
                $sku['export_tax_rebate'] = 0;
            }
            $inven_model->addall_data($data);
            //新增当月所有出口退税的sku
            foreach ($data as &$sku) {
                $sku['export_tax_rebate'] = 1;
            }
            $inven_model->addall_data($data);

            $inven_model->update_inventories($skus_arr);
        }
    }

    /**
     * 1.查出入库单信息,处理数据
     * 2.查出出库单信息,处理数据
     * 3.查出期初信息,处理数据
     * 4.遍历求期初成本,求期初数量
     * 期初库存
     * khq 2017.4.27
     */
    public function qichu_inventories() {
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        echo '正在计算期初,请稍等 '.date('Y-m-d H:i:s',time()).'</br>';
        $invent_model   = $this->inventories;      //期初库存model
        $stockIn_model  = $this->warehouseorders;  //入库model
        $stockOut_model = $this->deliveryorders;   //出库model
        $invent_model->delete_inventories();       //删除当月已经存在的sku
        $in_datas = $stockIn_model->get_qichu_in();
        $in_arr = array();                         //月采购入库数据
        foreach ($in_datas as $k=>$v) {            //拼接数组
            $key = strtoupper(trim($v['sku'])).'_'.$v['enterprise_dominant'].'_'.$v['export_tax_rebate'].'_'.$v['site_id'];
            $in_arr[$key] = $v;
        }
        unset($in_datas);
        $out_arr = array();                       //月销售出库数据
        $out_datas = $stockOut_model->get_qichu_out();
        foreach ($out_datas as $k=>$v) {          //拼接数组
            $key = strtoupper(trim($v['sku'])).'_'.$v['enterprise_dominant'].'_'.$v['export_tax_rebate'].'_'.$v['site_id'];
            $out_arr[$key] = $v;
        }
        unset($out_datas);
        $invent_datas = $invent_model->get_qichu_invent();
        $invent_arr = array();                    //上月期初数据
        foreach ($invent_datas as $k=>$v) {
            $key = $v['sku'].'_'.$v['enterprise_dominant'].'_'.$v['export_tax_rebate'].'_'.$v['site_id'];
            $invent_arr[$key] = $v;
        }
        unset($invent_datas);
        $qichu_arr = array();                   //本月期初
        foreach ($in_arr as $k=>$v) {           //遍历入库数据
            $inv_quantity  = 0;
            $out_quantity  = 0;
            $inv_cost      = 0;
            if($invent_arr[$k]){                //上月期初
                $inv_quantity = $invent_arr[$k]['all_quantity'];
                $inv_cost     = $invent_arr[$k]['all_cost'];
            }
            if($out_arr[$k]) {                  //出库
                $out_quantity = $out_arr[$k]['all_quantity'];
            }
            $quantity    = $v['all_quantity']+$inv_quantity;         //本月入库数量+上月期初数量
            $single_cost = ($v['all_cost']+$inv_cost)/$quantity;     //单个sku成本
            $cost        = $single_cost*($quantity-$out_quantity);   //期初成本

            $qichu_arr[] = array(
                'sku' => $v['sku'],
                'quantity' => $quantity-$out_quantity,
                'cost'     => $cost,
                'site_id'  => $v['site_id'],
                'sku_name' => $v['sku_name'],
                'sku_standard' => $v['sku_standard'],
                'supplier_id' => $v['supplier_id'],
                'inventory_date' => date('Y-m-01', time()),
                'export_tax_rebate' => $v['export_tax_rebate'],
                'enterprise_dominant' => $v['enterprise_dominant']
            );
            unset($invent_arr[$k]);
        }
        foreach ($invent_arr as $k=>&$v) {
            $qichu_arr[] = array(
                'sku'      => $v['sku'],
                'quantity' => $v['all_quantity'],
                'cost'     => $v['all_cost'],
                'site_id'  => $v['site_id'],
                'sku_name' => $v['sku_name'],
                'sku_standard'        => $v['sku_standard'],
                'supplier_id'         => $v['supplier_id'],
                'inventory_date'      => date('Y-m-01', time()),
                'export_tax_rebate'   => $v['export_tax_rebate'],
                'enterprise_dominant' => $v['enterprise_dominant']
            );
        }
        $invent_model->addall_data($qichu_arr);
        echo '期初处理完成,共插入 '.count($qichu_arr).'条数据 '.date('Y-m-d H:i:s',time());
    }

    public function crontab_qichu() {
        set_time_limit(0);
        header ( "Content-Type: text/html; charset=utf-8" );
        ini_set('memory_limit', '2048M');

        $invent_model = $this->balance;
        $stockIn_model  = $this->warehouseorders;  //入库model
        $stockOut_model = $this->deliveryorders;   //出库model

        $invent_model->delete_inventories();
        $in_datas = $stockIn_model->crontab_month_in();
        $in_arr = array();                         //月采购入库数据
        foreach ($in_datas as $k=>$v) {            //拼接数组
            $key = strtoupper(trim($v['sku'])).'_'.$v['enterprise_dominant'];
            $in_arr[$key] = $v;
        }
        unset($in_datas);
        $out_arr = array();                       //月销售出库数据
        $out_datas = $stockOut_model->crontab_month_out();
        foreach ($out_datas as $k=>$v) {          //拼接数组
            $key = strtoupper(trim($v['sku'])).'_'.$v['enterprise_dominant'];
            $out_arr[$key] = $v;
        }
        unset($out_datas);
        $invent_datas = $invent_model->get_inventory_cost();
        $invent_arr = array();                    //上月期初数据
        foreach ($invent_datas as $k=>$v) {
            $key = $v['sku'].'_'.$v['enterprise_dominant'];
            $invent_arr[$key] = $v;
        }
        unset($invent_datas);
        $qichu_arr = array();                   //本月期初
        foreach ($in_arr as $k=>$v) {           //遍历入库数据
            $inv_quantity  = 0;
            $out_quantity  = 0;
            $inv_cost      = 0;
            if($invent_arr[$k]){                //上月期初
                $inv_quantity = $invent_arr[$k]['totalQuantity'];
                $inv_cost     = $invent_arr[$k]['totalCost'];
            }
            if($out_arr[$k]) {                  //出库
                $out_quantity = $out_arr[$k]['totalQuantity'];
            }
            $quantity    = $v['totalQuantity']+$inv_quantity;         //本月入库数量+上月期初数量
            $single_cost = ($v['totalCost']+$inv_cost)/$quantity;     //单个sku成本
            $cost        = $single_cost*($quantity-$out_quantity);   //期初成本

            $qichu_arr[] = array(
                'sku' => $v['sku'],
                'quantity' => $quantity-$out_quantity,
                'cost'     => $cost,
                'sku_name' => $v['sku_name'],
                'inventory_date' => date('Y-m-01', time()),
                'enterprise_dominant' => $v['enterprise_dominant'],
                'single_price' => $single_cost
            );
            unset($invent_arr[$k]);
        }
        foreach ($invent_arr as $k=>&$v) {
            $out_quantity  = 0;

            if($out_arr[$k]) {
                $out_quantity = $out_arr[$k]['totalQuantity'];
            }

            $single_cost = ($v['totalCost'])/$v['totalQuantity'];     //单个sku成本
            $cost        = $single_cost*($v['totalQuantity']-$out_quantity);   //期初成本

            $qichu_arr[] = array(
                'sku'      => $v['sku'],
                'quantity' => $v['totalQuantity'] - $out_quantity,
                'cost'     => $cost,
                'sku_name' => $v['sku_name'] ? $v['sku_name'] : $out_arr[$k]['sku_name'],
                'inventory_date'      => date('Y-m-01', time()),
                'enterprise_dominant' => $v['enterprise_dominant'],
                'single_price' => $single_cost
            );

        }
        $invent_model->addall_data($qichu_arr);
        $result = array('code' => 0, 'info' => "插入成功");
        $output = json_encode($result, JSON_PRETTY_PRINT) . "\n";
        exit($output);
    }

    /**
     * @param array $_array
     * @param bool  $flag
     * @return mixed
     * 获取sku储位可用库存信息
     */
    public function get_inventories (&$_array = array (), $flag = TRUE) {
        $stockInModel       = $this->stockIn->get_storage_inventories();
        $stockInModel_count = clone $stockInModel;

        if ($flag) {
            $this->count = $stockInModel_count->count();            //数量

            $Page = new \Org\Util\Page($this->count, 20);           //实例化分页类 传入总记录数和每页显示的记录数(15)

            $this->page = $Page->show();                           // 分页显示输出

            $stockInModel->limit($Page->firstRow.','.$Page->listRows);
        }

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $stockInModel->select();
        return $result;
    }

    /**
     * @param $datas
     * 检查导入的盘点数据合法性
     * khq 2017.3.9
     */
    public function check_upload_data (&$datas) {
        $flag = TRUE;
        $str  = '';
        foreach ($datas as $k => $v) {
            if ($k == 1) {
                continue;
            }
            if ($v['A'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 SKU 为空,导入失败</br>';
            }
            if ($v['B'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 单据下载时间 为空,导入失败</br>';
            }
            if ($v['C'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 品名 为空,导入失败</br>';
            }
            if ($v['D'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 储位 为空,导入失败</br>';
            }
            if ($v['E'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 盘点日期 为空,导入失败</br>';
            }
            if ($v['F'] == '' && $v['F'] !== 0) {
                $flag = FALSE;
                $str .= '第'.$k.'行 库存量 为空,导入失败</br>';
            }
            if ($v['G'] == '' && $v['G'] !== 0) {
                $flag = FALSE;
                $str .= '第'.$k.'行 实际盘点量 为空,导入失败</br>';
            }
            if ($v['H'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 公司主体 为空,导入失败</br>';
            }
            if ($v['I'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 站点 为空,导入失败</br>';
            }
            if ($v['J'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 是否退税 为空,导入失败</br>';
            }
        }
        return array (
            'status'  => $flag,
            'message' => $str
        );
    }

    /**
     * @param $arr -导入文件数组
     * @return string
     *             khq 2017.3.9
     */
    public function upload_platform ($arr) {
        try {
            $datas        = $this->upload_platform_detail($arr);
            $check_result = $this->check_upload_resolve_data($datas);                   //检查解析最终数据的纯洁性
            if ($check_result['flag'] == FALSE) {                                           //导入的数据在系统不存在
                return array (
                    'status'  => 401,
                    'message' => $check_result['message']
                );
            }
            $deficit = array ();                                                         //盘亏
            $win     = array ();                                                         //盘盈
            foreach ($datas as $k => $v) {
                if ($v['status'] == 1) {                                                    //盘亏出库
                    $i = 2;                                                              //盘亏出库的方法不读取前两行
                    $i ++;
                    $deficit[$i] = array (
                        'A' => 20,
                        //盘点类型:盘亏出库
                        'B' => $v['sku'],
                        //sku
                        'C' => abs($v['num']),
                        //出库数量
                        'D' => $this->nowtime,
                        //出库时间
                        'E' => $v['storage_position'],
                        //储位
                        'F' => '盘亏出库',
                        //备注
                        'G' => $v['site_id'],
                        //站点
                        'H' => $v['enterprise_dominant'],
                        //公司主体
                        'I' => $v['export_tax_rebate']
                        //是否退税
                    );
                } elseif ($v['status'] == 2) {                                              //盘盈入库
                    $win[] = array (
                        'warehouse_date'      => date('Y-m-d', time()),
                        'op_time'             => $this->nowtime,
                        'warehouse_quantity'  => $v['num'],
                        'available_quantity'  => $v['num'],
                        'storage_position'    => $v['storage_position'],
                        'enterprise_dominant' => $v['enterprise_dominant'],
                        //公司主体
                        'export_tax_rebate'   => $v['export_tax_rebate'],
                        //是否退税
                        'site_id'             => $v['site_id'],
                        'sku'                 => $v['sku'],
                        'sku_name'            => $v['sku_name'],
                        'type'                => 30,
                        //盘盈入库
                        'warehouse_man'       => $_SESSION['current_account']['role_id'],
                        'transfer_hopper_id'  => 1,
                    );
                }
            }
            if (!empty($deficit)) {
                D('StockOut', 'Service')->upload_platform($deficit);                     //批量出库
            }
            if (!empty($win)) {
                $this->stockIn->batch_create($win);                                     //批量入库
            }
            D('Pandians', 'Model')->batch_create($datas);                                //新建盘点表
            $this->pandians->model->commit();
            return array ('status' => 200);
        } catch (Exception $e) {
            $this->pandians->model->rollback();
            print $e->getMessage();
            return array ('status' => 403);
        }
    }

    /**
     * @param $arr
     * @return array
     * 上传的库存盘点数据
     * khq 2017.3.9
     */
    public function upload_platform_detail (&$arr) {
        $datas = array ();
        foreach ($arr as $K => $v) {
            if ($K >= 2) {
                $v       = PrepareneedsService::trim_array($v);                                  //过滤空格
                $num     = intval(trim($v['G'])) - intval(trim($v['F']));                          //盘点数量差额
                $data    = array (
                    'sku'                 => strtoupper(mysql_escape_string($v['A'])),
                    'download_time'       => date('Y-m-d', strtotime(trim($v['B']))),
                    //单据下载时间
                    'sku_name'            => mysql_escape_string($v['C']),
                    //品名
                    'storage_position'    => mysql_escape_string($v['D']),
                    //储位
                    'pd_time'             => date('Y-m-d', strtotime(trim($v['E']))),
                    //盘点日期
                    'quantity2'           => intval(trim($v['F'])),
                    //库存量
                    'quantity'            => intval(trim($v['G'])),
                    //实际盘点量
                    'enterprise_dominant' => mysql_escape_string($v['H']),
                    //公司主体
                    'site_id'             => trim($v['I']),
                    //站点
                    'export_tax_rebate'   => mysql_escape_string($v['J']),
                    //是否出口退税
                    'upload_time'         => $this->nowtime,
                    //上传时间
                    'user_id'             => $_SESSION['current_account']['id'],
                    //操作人
                    'status'              => $num > 0?2:($num == 0?3:1),
                    //盘点状态 1盘亏2盘盈3正常
                    'num'                 => abs($num),
                );
                $datas[] = $data;
            }
        }
        return $datas;
    }

    /**
     * @param $datas
     * @return array
     * 检查通过分解后的数据
     * khq 2017.1.11
     */
    public function check_upload_resolve_data (&$datas) {
        $flag        = TRUE;
        $str         = '';
        $sites       = PublicInfoService::get_site_array();                                       //站点
        $sites       = array_flip($sites);
        $company_arr = PublicdataService::get_enterprise_dominants();                       //公司主体
        foreach ($datas as $k => $v) {
            $site_id = $sites[$v['site_id']];
            if ($site_id) {
                $datas[$k]['site_id'] = $site_id;
            } else {
                $flag = FALSE;
                $str .= '第'.($k + 2).'行 站点 不存在,导入失败</br>';
            }
            $enterprise_dominant = '';
            foreach ($company_arr as $c => $d) {
                if ($v['enterprise_dominant'] == $d) {
                    $enterprise_dominant = $c;
                }
            }
            if ($enterprise_dominant) {
                $datas[$k]['enterprise_dominant'] = $enterprise_dominant;
            } else {
                $flag = FALSE;
                $str .= '第'.($k + 2).'行 公司主体 不存在,导入失败</br>';
            }
            if ($v['sku'] == '') {
                $flag = FALSE;
                $str .= '第'.($k + 2).'行 sku 不存在,导入失败</br>';
            }
            if ($v['export_tax_rebate'] == '出口退税' || $v['export_tax_rebate'] == '非出口退税') {
                $datas[$k]['export_tax_rebate'] = $v['export_tax_rebate'] == '出口退税'?1:0;
            } else {
                $flag = FALSE;
                $str .= '第'.($k + 2).'行 出口退税 填写不正确,导入失败</br>';
            }
            unset($site_id);
            unset($enterprise_dominant);
            //先不验证sku对应储位的数量了,因为是刚刚导出来的咯.
        }
        return array (
            'flag'    => $flag,
            'message' => $str
        );
    }

    /**
     * 获取sku状态和位置
     * @param $sku
     * @return mixed
     */
    public function getSkuStatusAndPlace ($_array) {
        $sku_model = $this->sku_cnname;
        $sku       = array ($_array['sku']);
        return $sku_model->get_sku_warehouse_and_status($sku);
    }

    /**
     * @param array $_array
     * @param bool  $flag
     * @return mixed
     * 获取各sku在不同储位对应可用库存
     * khq 2017.3.23
     */
    public function inventories_data (&$_array = array (), $flag = TRUE) {
        $inventoriesModel       = $this->get_inventories_model($_array);
        $inventoriesModel_count = clone $inventoriesModel;
        if ($flag) {
            $data        = $inventoriesModel_count->field('sku')
                ->select();        //数量
            $this->count = count($data);

            $Page = new \Org\Util\Page($this->count, 15);                    //实例化分页类 传入总记录数和每页显示的记录数(20)

            $this->page = $Page->show();                                    // 分页显示输出

            $inventoriesModel->limit($Page->firstRow.','.$Page->listRows);
        }
        $result = $inventoriesModel->field('wms_warehouseorders.sku, sku_name, export_tax_rebate, enterprise_dominant, storage_position,
                 SUM(available_quantity) AS all_available_quantity,skusystem_statuss.status,
                 wms_warehouseorders.site_id as site_id')
            ->join('skusystem_status_skuss ON wms_warehouseorders.sku=skusystem_status_skuss.sku', 'LEFT')
            ->join('skusystem_statuss ON skusystem_status_skuss.status_id=skusystem_statuss.id', 'LEFT')
            ->select();
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $this->format_inventories_data($result);
        return $result;
    }

    /**
     * @param $_array
     * @return \Model
     * 获取入库单储位对应sku库存的model
     * khq 2017.3.23
     */
    public function get_inventories_model ($_array) {
        $model = M('warehouseorders', 'wms_', 'fbawarehouse');
        if ($_array) {
            $_array = array_filter($_array);
            $_array = PrepareneedsService::trim_array($_array);
        }
        foreach ($_array as $key => $_arr) {
            switch ($key) {
                case 'warehouse_date_to':
                    $_array['wms_warehouseorders.warehouse_date'][] = array (
                        'elt',
                        $_arr
                    );
                    unset($_array['warehouse_date_to']);
                    break;
            }
        }
        if ($_array['sku']) {
            $_array['wms_warehouseorders.sku'] = $_array['sku'];
            unset($_array['sku']);
        }
        $_array['available_quantity'][] = array (
            'neq',
            0
        );
        $model->where($_array)
            ->group('wms_warehouseorders.sku, storage_position, export_tax_rebate, enterprise_dominant,
            wms_warehouseorders.site_id');
        return $model;
    }
    /**
     * 格式化数据
     */
    public function format_inventories_data($data,$flag = true){
        //格式化
        $company_arr = PublicdataService::get_enterprise_dominants();
        $sites       = PublicInfoService::get_site_array();

        foreach($data as &$_data){//$_data['sku']
            if(!$flag){
                $storage_inventories  = $this->stockIn->get_storage_inventories('',$_data['sku'],
                    $_data['enterprise_dominant'] ,$_data['site_id'],$_data['export_tax_rebate'])->select();

                $avaliable_quantity  = PublicdataService::i_array_column($storage_inventories,'all_available_quantity');
                $_data['avaliable_quantity'] = array_sum($avaliable_quantity);
                $_data['sku_name'] = $storage_inventories[0]['sku_name'];
                $_data['details']  = $storage_inventories;
                $condition = array(
                    'sku'                 => $_data['sku'],
                    'enterprise_dominant' => $_data['enterprise_dominant'],
                    'export_tax_rebate'   => $_data['export_tax_rebate'],
                    'site_id'             => $_data['site_id'],
                );
                if($_data['export_tax_rebate'] == 1){
                    $_data['occupy_quantity'] = $this->fbaInboundShipmentPlan->get_tax_sku_occupied_num($condition)
                        + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($condition, 1);
                }else{
                    $_data['occupy_quantity'] = $this->fbaInboundShipmentPlan->get_sku_occupied_num($condition)
                        + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($condition, 0);
                }

            }
            $_data['export_tax_rebate']   = $_data['export_tax_rebate']==1?'出口退税':'非出口退税';
            $_data['enterprise_dominant'] = $company_arr[$_data['enterprise_dominant']];
            $_data['site_id']             = $sites[$_data['site_id']];
        }
        return $data;
    }

   /*public function format_inventories_data2 ($data, $flag = TRUE) {
        //格式化
        $company_arr = PublicdataService::get_enterprise_dominants();
        $sites       = PublicInfoService::get_site_array();
        if (!$flag) {
            $storage_inventories = $this->stockIn->get_all_storage_inventories();
        }
        foreach ($data as &$_data) {
            if (!$flag) {
                $_data['details'] = array ();
                foreach ($storage_inventories as $val) {
                    if ($_data['sku'] == $val['sku'] && $_data['enterprise_dominant'] == $val['enterprise_dominant'] && $_data['site_id'] == $val['site_id'] && $_data['export_tax_rebate'] == $val['export_tax_rebate']) {
                        $_data['avaliable_quantity'] += $val['all_available_quantity'];
                        $_data['sku_name']  = $val['sku_name'];
                        $details            = array (
                            'storage_position'       => $val['storage_position'],
                            'all_available_quantity' => $val['all_available_quantity'],
                        );
                        $_data['details'][] = $details;
                    }
                }
            }
            $_data['export_tax_rebate']   = $_data['export_tax_rebate'] == 1?'出口退税':'非出口退税';
            $_data['enterprise_dominant'] = $company_arr[$_data['enterprise_dominant']];
            $_data['site_id']             = $sites[$_data['site_id']];
        }
        return $data;
    }*/

    /**
     * @param $detail_data
     * 导出sku,储位,库存信息
     * khq 2017.3.10
     */
    public function download_detail (&$detail_data) {

        set_time_limit(0);
        ini_set('memory_limit', '2048M');

        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $fileName = "库存盘点(".date('Ymd', time()).")";

        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$fileName.csv");
        //输出表头
        $table_head = array (
            'SKU',
            '中文名称',
            '储位',
            '站点',
            '实际库存量',
            '是否出口退税',
            '公司主体',
            '销售状态'
        );
        fputcsv($output, $table_head);
        //输出每一行数据到文件中
        foreach ($detail_data as $info) {
            $data = array (
                'sku'                    => $info['sku'],
                'sku_name'               => str_replace(array("\r\n", "\r", "\n",","), '',$info['sku_name']),
                'storage_position'       => $info['storage_position'],
                'site_id'                => $info['site_id'],
                'all_available_quantity' => $info['all_available_quantity'],
                'export_tax_rebate'      => $info['export_tax_rebate'],
                'enterprise_dominant'    => $info['enterprise_dominant'],
                'status'                 => $info['status']
            );
            fputcsv($output, array_values($data));
        }
        //关闭文件句柄
        fclose($output) or die("can't close php://output");
        exit;
    }


    /**
     * @param $detail_data
     * sku实时库存导出下载
     */
    public function sku_real_inventory_download ($_array) {
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        $filename = "sku实时报表(".date('Ymd', time()).")";
        $title    = array (
            'sku',
            '采购名称',
            'sku实时库存',
            '入库单可用库存',
            'sku实际可用库存',
            '占用库存',
            '是否退税',
            '站点',
            '公司主体'
        );
//        header("Content-type:text/csv");
//        header("Content-Disposition:attachment;filename=$filename.csv");
        $data = "";
        foreach ($title as $value) {
            $data .= $value.",";
        }
        $data .= "\n";//表头换行
        $i      = 0;
        $sql    = "SELECT a.`sku` as sku, b.sku_name as sku_name, a.`quantity` as quantity, 
        SUM(b.`available_quantity`) as available_quantity, a.`export_tax_rebate` as export_tax_rebate, 
        b.`site_id` as site_id, a.`enterprise_dominant` as enterprise_dominant
        FROM 
        fbawarehouse.wms_real_inventories a 
        LEFT JOIN 
        fbawarehouse.wms_warehouseorders b 
        ON 
        a.warehouseid=b.warehouseid AND a.`sku` = b.`sku` 
        AND a.`enterprise_dominant` = b.`enterprise_dominant` 
        AND a.`export_tax_rebate` = b.`export_tax_rebate` 
        AND a.`site_id` = b.`site_id` ";
        $where = " where 1 ";
        if ($_array['sku']){
            $sku_s = '';
            foreach($_array['sku'][1] as $sku){
                $sku_s .= "'".$sku."',";
            }
            $sku_s = rtrim($sku_s,",");
            $where .= " and a.sku in({$sku_s}) ";
        }
        if ($_array['enterprise_dominant']){
            $where .= " and a.enterprise_dominant={$_array['enterprise_dominant']} ";
        }
        if ($_array['export_tax_rebate']==1){
            $where .= " and a.export_tax_rebate=1} ";
        }elseif($_array['export_tax_rebate']==-1){
            $where .= " and a.export_tax_rebate=0} ";
        }
        if ($_array['site_id']){
            $where .= " and a.site_id={$_array['site_id']} ";
        }
        $sql.=$where;
        $sql.= "GROUP BY 
        a.sku,a.export_tax_rebate, a.enterprise_dominant, a.site_id;";

        $result = PublicPlugService::download($sql);

        if(mysqli_num_rows($result)<=2000){  //判断条数
            header("Content-type:text/csv");
            header("Content-Disposition:attachment;filename=$filename.csv");
            $company_arr = PublicdataService::get_enterprise_dominants();
            $sites       = PublicInfoService::get_site_array();
            while ($row = mysqli_fetch_array($result)) {
                $i ++;//序号
                //控制一行连续输出
                $condition = array(
                    'sku'                 => $row['sku'],
                    'enterprise_dominant' => $row['enterprise_dominant'],
                    'export_tax_rebate'   => $row['export_tax_rebate'],
                    'site_id'             => $row['site_id'],
                );
                if($row['export_tax_rebate'] == 1){
                    $row['occupy_quantity'] = $this->fbaInboundShipmentPlan->get_tax_sku_occupied_num($condition)
                        + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($condition, 1);
                }else{
                    $row['occupy_quantity'] = $this->fbaInboundShipmentPlan->get_sku_occupied_num($condition)
                        + $this->fbaPrepareNeedsDetails->get_sku_occupied_num($condition, 0);
                }

                $row['export_tax_rebate']   = $row['export_tax_rebate'] == 1?'出口退税':'非出口退税';
                $row['enterprise_dominant'] = $company_arr[$row['enterprise_dominant']];
                $row['site_id']             = $sites[$row['site_id']];
                $row['actual_avaliable_quantity'] = $row['quantity']-$row['occupy_quantity'];

                $data .= $row['sku'].",".str_replace(array("\r\n", "\r", "\n",","), '',$row['sku_name']).",".$row['quantity'].",".$row['available_quantity'].",".
                    $row['actual_avaliable_quantity'].",".$row['occupy_quantity'].",".$row['export_tax_rebate'].
                    ",".$row['site_id'].",".$row['enterprise_dominant'];
                $data .= "\n";//控制换行
            }var_dump($data);exit;
            ob_end_flush();
            //关闭数据库资源
            mysqli_close(PublicPlugService::$link);
            echo $data;
            exit;
        } else {
            echo "<script>alert('数据超过两千行,请分批下载');window.location.href='sku_real_inventory';</script>";
        }

    }
    /**
     * 描述:  FBA库存数据插入
     * 作者: kelvin
     */
    public function fbaInventoryAdd() {
        $model = M('','','fbawarehouse');
        $where = array(
            'date' =>date('Y-m-d')
        );
        if($model->table('fba_inventory_monitoring')->where($where)->find()){
            echo "Data already exists";die;
        }
        //采购在途
        $sql = "SELECT '采购在途',pd.`sku`,sum(`quantity` - `ware_quantity`) AS quantity, d.num as money
            FROM `wms_purchaseorder_details` AS pd 
            LEFT JOIN wms_purchaseorders AS p ON p.id = pd.purchaseorder_id 
            left join skusystem_price d on d.sku = pd.sku
            WHERE p.store = 11 
            AND p.status < 70 
            AND pd.status <= 65 
            AND p.status >= 20 
            AND pd.status >=20 
            and p.pass not in (1,3,4)
            and pd.sku <> 'F%'
            group by pd.sku";
        $cgzt_data = $model->query($sql);
        //中转仓库存
        $zzc_data = $model->table('wms_warehouseorders a')
            ->join("left join skusystem_price b on b.sku = a.sku")
            ->where("available_quantity > 0")
            ->group('a.sku')
            ->field("'中转仓库存',a.sku,SUM(`available_quantity`) as quantity,b.num as money")
            ->select();
        //国际在途
        $gjzt_date = $model->table('api_report_unsuppressed_inventory')
            ->where('create_time LIKE "%' . date('Y-m-d') . '%"')
            ->field('LEFT(Max(create_time),13) AS date')
            ->find();
        $gjzt_data = $model->table('api_report_unsuppressed_inventory a')
            ->join('LEFT JOIN amazonorder_account_troop_site as b ON a.`account_id` = b.`account_id`')
            ->join('LEFT JOIN amazonorder_sites as c ON c.id = b.site_id')
            ->join("LEFT JOIN api_account_seller_sku AS aass ON a.account_id = aass.account_id AND a.sku = aass.seller_sku")
            ->join("LEFT JOIN skusystem_price d on d.sku = aass.private_sku")
            ->where("(a.afn_inbound_working_quantity + a.afn_inbound_shipped_quantity + a.afn_inbound_receiving_quantity) > 0 
                      AND a.sku != '' AND a.create_time LIKE '" . $gjzt_date['date'] . "%' 
                      AND aass.private_sku IS NOT NULL")
            ->group('aass.private_sku')
            ->field("'国际在途',aass.private_sku as sku,SUM(a.afn_inbound_working_quantity + a.afn_inbound_shipped_quantity + a.afn_inbound_receiving_quantity) as quantity, d.num as money")
            ->select();
        //站点库存汇总
        $kchz_date = $model->table('api_report_inventory')
            ->where('create_time LIKE "%' . date('Y-m-d') . '%"')
            ->field('LEFT(Max(create_time),13) AS date')
            ->find();
        $kchz_data = $model->table('api_report_inventory a')
            ->join("LEFT JOIN api_account_seller_sku AS aass ON a.account_id = aass.account_id AND a.sku = aass.seller_sku")
            ->join("LEFT JOIN skusystem_price d on d.sku = aass.private_sku")
            ->where("a.sku != '' AND a.`quantity_for_local_fulfillment` > 0 
                     AND a.create_time LIKE '" . $kchz_date['date'] . "%' 
                     AND aass.private_sku IS NOT NULL" )
            ->group('aass.private_sku')
            ->field("'站点库存汇总',aass.private_sku AS sku,SUM(a.quantity_for_local_fulfillment) as quantity,d.num as money")
            ->select();
        $down = array_merge($cgzt_data,$zzc_data,$gjzt_data,$kchz_data);
        S('fbaInventoryDown',NULL);
        S('fbaInventoryDown',$down,86400);
        $result = array();
        $result['date'] = date('Y-m-d');
        $result['create_time'] = date('Y-m-d H:i:S');
        $result['cg_sku'] = count($cgzt_data);
        $result['gjzt_sku'] = count($gjzt_data);
        $result['hz_sku'] = count($kchz_data);
        $result['zzc_sku'] = count($zzc_data);
        foreach($cgzt_data as &$c){
            $result['cg_pcs'] += $c['quantity'];
            $result['cg_money'] += $c['money']*$c['quantity'];
        }
        foreach($zzc_data as &$v){
            $result['zzc_pcs'] += $v['quantity'];
            $result['zzc_money'] += $v['money']*$v['quantity'];
        }
        foreach($gjzt_data as &$g){
            $result['gjzt_pcs'] += $g['quantity'];
            $result['gjzt_money'] += $g['money']*$g['quantity'];
        }
        foreach($kchz_data as &$k){
            $result['hz_pcs'] += $k['quantity'];
            $result['hz_money'] += $k['money']*$k['quantity'];
        }
        $result['all_pcs'] =  $result['zzc_pcs'] +  $result['gjzt_pcs'] +  $result['hz_pcs'];
        $result['all_money'] =  $result['zzc_money'] +  $result['gjzt_money'] +  $result['hz_money'];
        $model->table('fba_inventory_monitoring')->add($result);

    }
    /**
     * 描述: FBA库存数据查询
     * 作者: kelvin
     */
    public function fbaInventory($array = array()) {
        $model = M('inventory_monitoring','fba_','fbawarehouse');
        if($array['claim_arrive_time_from'] && $array['claim_arrive_time_to']){
            $where['date'] = array(
                array('egt',$array['claim_arrive_time_from']),
                array('elt',$array['claim_arrive_time_to']),
            );
            return $model->order('date desc')->where($where)->select();
        }else{
            return $model->order('date desc')->limit(7)->select();
        }

    }

    /**
     * 描述：获取某月的库存成本报表
     * 作者：橙子
     */
    public function getInventoryCostDetail($array, $flag = false) {
        $stock_in_type = BaseInfoService::stock_in_type();
        $stock_out_type = BaseInfoService::stock_out_type();

        $inventory_data = $this->formatInventoryCostData($this->balance->get_inventory_cost($array));
        $inventory_data_end = $this->formatInventoryCostData($this->balance->get_inventory_cost_end($array));
        $stockIn_data = $this->get_sku_cost_type_row($this->stockIn->get_month_in($array), 'in');
        $stockOut_data = $this->get_sku_cost_type_row($this->deliveryorders->get_month_out($array), 'out');

        $inventoryCostDetail = array();
        $tempArray = array();
        $skuInTotalCost = 0;
        $skuInTotalQuantity = 0;
        $skuOutTotalCost = 0;
        $skuOutTotalQuantity = 0;

        if (!empty($inventory_data)) {
            foreach ($inventory_data as $key => $data) {
                $tempArray['sku'] = $data['sku'];
                $tempArray['sku_name'] = $data['sku_name'];
                $tempArray['enterprise_dominant'] = $data['enterprise_dominant'];
                $tempArray['beginning_quantity'] = $data['totalQuantity'];
                $tempArray['beginning_cost'] = $data['totalCost'];
                $tempArray['end_quantity'] = isset($inventory_data_end[$key]) ? $inventory_data_end[$key]['totalQuantity'] : 0;
                $tempArray['end_cost'] = isset($inventory_data_end[$key]) ? $inventory_data_end[$key]['totalCost'] : 0;

                foreach ($stock_in_type as $k => $v) {
                    $tempArray['in_' . $k . '_quantity'] = isset($stockIn_data[$key]['in_' . $k . '_quantity'])
                        ? $stockIn_data[$key]['in_' . $k . '_quantity'] : 0;
                    $tempArray['in_' . $k . '_cost'] = isset($stockIn_data[$key]['in_' . $k . '_cost'])
                        ? $stockIn_data[$key]['in_' . $k . '_cost'] : 0.00;

                    $skuInTotalQuantity += $tempArray['in_' . $k . '_quantity'];
                    $skuInTotalCost += $tempArray['in_' . $k . '_cost'];
                }

                $tempArray['inTotalQuantity'] = $skuInTotalQuantity;
                $tempArray['inTotalCost'] = $skuInTotalCost;

                if (($tempArray['beginning_quantity'] + $skuInTotalQuantity)) {
                    $outSingleCost = ($tempArray['beginning_cost'] + $skuInTotalCost) / ($tempArray['beginning_quantity'] + $skuInTotalQuantity);
                } else
                    $outSingleCost = 0;


                foreach ($stock_out_type as $k => $v) {
                    $tempArray['out_' . $k . '_quantity'] = isset($stockOut_data[$key]['out_' . $k . '_quantity'])
                        ? $stockOut_data[$key]['out_' . $k . '_quantity'] : 0;
                    $tempArray['out_' . $k . '_cost'] = $outSingleCost * $tempArray['out_' . $k . '_quantity'];

                    $skuOutTotalQuantity += $tempArray['out_' . $k . '_quantity'];
                    $skuOutTotalCost += $tempArray['out_' . $k . '_cost'];
                }

                $tempArray['outTotalQuantity'] = $skuOutTotalQuantity;
                $tempArray['outTotalCost'] = $skuOutTotalCost;

                $inventoryCostDetail[] = $tempArray;
                unset($stockIn_data[$key]);
                unset($stockOut_data[$key]);
                unset($inventory_data_end[$key]);
            }
        }

        if (!empty($stockIn_data)) {
            foreach ($stockIn_data as $key => $data) {
                $tempArray['sku'] = $data['sku'];
                $tempArray['sku_name'] = $data['sku_name'];
                $tempArray['enterprise_dominant'] = $data['enterprise_dominant'];
                $tempArray['beginning_quantity'] = 0;
                $tempArray['beginning_cost'] = 0.00;
                $tempArray['end_quantity'] = isset($inventory_data_end[$key]) ? $inventory_data_end[$key]['totalQuantity'] : 0;
                $tempArray['end_cost'] = isset($inventory_data_end[$key]) ? $inventory_data_end[$key]['totalCost'] : 0;

                foreach ($stock_in_type as $k => $v) {
                    $tempArray['in_' . $k . '_quantity'] = isset($data['in_' . $k . '_quantity'])
                        ? $data['in_' . $k . '_quantity'] : 0;
                    $tempArray['in_' . $k . '_cost'] = isset($data['in_' . $k . '_cost'])
                        ? $data['in_' . $k . '_cost'] : 0.00;

                    $skuInTotalQuantity += $tempArray['in_' . $k . '_quantity'];
                    $skuInTotalCost += $tempArray['in_' . $k . '_cost'];
                }

                $tempArray['inTotalQuantity'] = $skuInTotalQuantity;
                $tempArray['inTotalCost'] = $skuInTotalCost;

                $outSingleCost = $skuInTotalQuantity ? $skuInTotalCost/$skuInTotalQuantity : 0;

                foreach ($stock_out_type as $k => $v) {
                    $tempArray['out_' . $k . '_quantity'] = isset($stockOut_data[$key]['out_' . $k . '_quantity'])
                        ? $stockOut_data[$key]['out_' . $k . '_quantity'] : 0;
                    $tempArray['out_' . $k . '_cost'] = $outSingleCost * $tempArray['out_' . $k . '_quantity'];
                }

                $tempArray['outTotalQuantity'] = $skuOutTotalQuantity;
                $tempArray['outTotalCost'] = $skuOutTotalCost;

                $inventoryCostDetail[] = $tempArray;

            }
        }

        if(!$flag) {
            $this->count = count($inventoryCostDetail);

            $Page = new \Org\Util\Page($this->count, 15);                    //实例化分页类 传入总记录数和每页显示的记录数(20)

            $this->page = $Page->show();                                    // 分页显示输出

            $inventoryCostDetail = array_slice($inventoryCostDetail,$Page->firstRow,$Page->listRows);
        }

        return $inventoryCostDetail;
    }

    public function get_sku_cost_type_row($data, $type){
        if(empty($data)) return $data;

        $enterprise_dominant = BaseInfoService::enterprise_dominant();

        $row = array();
        foreach ($data as $_data) {
            $key = strtoupper($_data['sku'] . ':' . $_data['enterprise_dominant']);
            $row[$key]['sku'] = $_data['sku'];
            $row[$key]['sku_name'] = $_data['sku_name'];
            $row[$key]['enterprise_dominant'] = $enterprise_dominant[$_data['enterprise_dominant']];
            $row[$key][$type . '_' . $_data['type'] . '_quantity'] = $_data['totalQuantity'];
            $row[$key][$type . '_' . $_data['type'] . '_cost'] = $_data['totalCost'];
        }

       return $row;
    }

    public function formatInventoryCostData($data) {
        if(empty($data)) return $data;

        $enterprise_dominant = BaseInfoService::enterprise_dominant();
        $format_data = array();

        foreach($data as $_data) {
            $key = strtoupper($_data['sku'] . ':' . $_data['enterprise_dominant']);
            $format_data[$key] = $_data;
            $format_data[$key]['enterprise_dominant'] = $enterprise_dominant[$_data['enterprise_dominant']];
        }

        return $format_data;

    }

    public function downloadInventoryCostDetail($inventoryCostDetail, $date) {
        set_time_limit(0);
        ini_set('memory_limit','1024M');
        vendor('PHPExcel.PHPExcel.IOFactory');

        $stock_in_type = BaseInfoService::stock_in_type();
        $stock_out_type = BaseInfoService::stock_out_type();

        $firstLine_in = array();
        $firstLine_out = array();

        $PHPExcel = new \PHPExcel();
        $fileName = $date ? $date . "月度库存成本报表" : date("Y-m", strtotime("-1 month")) . "月度库存成本报表";
        $firstLine = array(
            "sku" => "SKU",
            "sku_name" => "SKU名称",
            "enterprise_dominant" => "公司主体",
            "beginning_quantity" => "期初数量",
            "beginning_cost" => "期初成本",
        );

        foreach($stock_in_type as $type => $name) {
            $firstLine_in['in_' . $type . '_quantity'] = $name . "数量";
            $firstLine_in['in_' . $type . '_cost'] = $name . "成本";
        }

        $firstLine_out['inTotalQuantity'] = "入库数量合计";
        $firstLine_out['inTotalCost'] = "入库成本合计";

        foreach($stock_out_type as $type => $name) {
            $firstLine_out['out_' . $type . '_quantity'] = $name . "数量";
            $firstLine_out['out_' . $type . '_cost'] = $name . "成本";
        }

        $firstLine_out['outTotalQuantity'] = "出库数量合计";
        $firstLine_out['outTotalCost'] = "出库成本合计";

        $firstLine_out['end_quantity'] = "期末数量";
        $firstLine_out['end_cost'] = "期末成本";

        $firstLine = array_merge($firstLine, $firstLine_in, $firstLine_out);

        $objActSheet =$PHPExcel->setActiveSheetIndex(0);
        $objActSheet->setTitle($fileName);

        $r = 'A';
        foreach($firstLine as $v){
            $objActSheet->setCellValue($r.'1',$v);
            $r++;
        }
        $i = 2;
        foreach($inventoryCostDetail as $value)
        {
            /* excel文件内容 */
            $j = 'A';
            foreach ($firstLine as $key => $v) {
                $objActSheet->setCellValue($j.$i,$value[$key]);
                $j++;
            }
            $i++;
        }

        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename='.$fileName.'.xls');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;
    }
}